package entity

import (
	"context"
	"go_iot/apps/base"
	"go_iot/pkg/global"
	"time"

	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/bson/primitive"
)

type Product struct {
	base.Base
	Name           string    `json:"name" validate:"required" gorm:"column:name"`
	Description    *string   `json:"desc" gorm:"column:description"`
	UserId         int       `json:"user" gorm:"column:user_id"`
	CreatedAt      time.Time `json:"create" gorm:"column:created_at"`
	AccessProtocol string    `json:"access" gorm:"column:access_protocol"`
	DataProtocol   string    `json:"data" gorm:"column:data_protocol"`
	TransMethod    string    `json:"method" gorm:"column:trans_method"`
}

type ProductProfile struct {
	ID        primitive.ObjectID `json:"key" bson:"_id"`
	Type      string             `json:"type" bson:"type"`
	ProductId string             `json:"product" bson:"product_id"`
	Profile   any                `json:"profile"`
}

type ModbusProfile struct {
	Name    string  `json:"name" bson:"name"`
	Station int     `json:"station" bson:"station"`
	Code    int     `json:"code" bson:"code"`
	Address int     `json:"address" bson:"address"`
	Number  int     `json:"num" bson:"num"`
	Unit    string  `json:"unit" bson:"unit"`
	Scale   float32 `json:"scale" bson:"scale"`
	Product string  `json:"product" bson:"-"`
}

func (Product) TableName() string {
	return "products"
}

func (p *Product) SearchMap() map[string]any {
	var m = map[string]any{}
	if p.UserId < 1 {
		return nil
	}
	m["user_id = ?"] = p.UserId
	if p.Name != "" {
		m["name like ?"] = "%" + p.Name + "%"
	}

	return m
}

func (m ProductProfile) CreateModbusItem(ctx context.Context) error {
	m.ID = primitive.NewObjectID()
	_, err := global.MongoDb.Collection("profile").InsertOne(ctx, m)
	return err
}

func GetProductProfile(ctx context.Context, t string, product string) ([]ProductProfile, error) {
	f := primitive.E{
		Key:   "product_id",
		Value: product,
	}

	f2 := primitive.E{
		Key:   "type",
		Value: t,
	}
	filer := bson.D{f, f2}
	cursor, err := global.MongoDb.Collection("profile").Find(ctx, filer)
	if err != nil {
		return nil, err
	}

	var p []ProductProfile
	if err = cursor.All(ctx, &p); err != nil {
		return nil, err
	}
	return p, nil
}

func DelProductProfile(ctx context.Context, id string) error {
	f := primitive.E{
		Key:   "_id",
		Value: id,
	}

	filer := bson.D{f}
	_, err := global.MongoDb.Collection("profile").DeleteOne(ctx, filer)
	if err != nil {
		return err
	}

	return nil
}
